/* diceroll.c -- 掷骰子模拟程序 */
/* 与 mandydice.c 一起编译 */
#include "diceroll.h"
#include <stdio.h>
#include <stdlib.h>             /* 提供库函数rand()的原型 */

int roll_count = 0;             /* 外部链接 */

static int rollem(int sides)    /* 该函数属于该文件私有 */
{
    int roll;

    roll = rand() % sides + 1;
    ++roll_count;               /* 计算函数调用次数 */

    return roll;
}

int roll_n_dice(int dice, int sides)
{
    int d;
    int total = 0;
    if (sides < 2)
    {
        printf("Need at least 2 sides.\n");
        return -2;
    }
    
    if (dice < 1)
    {
        printf("Need at least 1 die.\n");
        return -1;
    }
    
    for (size_t d = 0; d < dice; d++)
    {
        total += rollem(sides);
    }

    return total;
}

#include <time.h>           /* 为time()提供原型 */

int main(void)
{
    int dice, roll;
    int sides;
    int status;

    srand((unsigned int) time(0));  /* 随机种子 */
    printf("Enter the number of sides per die, 0 to stop.\n");
    while (scanf("%d", &sides) == 1 && sides > 0)
    {
        printf("How many dice?\n");
        if ((status = scanf("%d", &dice)) != 1)
        {
            if (status == EOF)
            {
                break;
            }
            else
            {
                printf("You should have entered an integer.");
                printf(" Let's begin again.\n");
                while (getchar() != '\n')
                    continue;       /* 处理错误的输入 */
                printf("How many sides? Enter 0 to stop.\n");
                continue;           /* 进入循环的下一轮迭代 */
            }
        }
        roll = roll_n_dice(dice, sides);
        printf("You have rolled a %d using %d %d-sided dice.\n", roll, dice, sides);
        printf("How many sides? Enter 0 to stop.\n");
    }
    printf("The rollem() function was called %d times\n", roll_count);

    printf("GOOD FORTUNE TO YOU!\n");

    return 0;
}